<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/1/9
 * Time: 下午3:39
 */

namespace Biz\model\trade;

use Biz\model\trade\OrderGoods as mOrderGoods;
use Doraemon\tools\Log;
use Medoo\Medoo;
use Biz\model\trade\OrderRefund as mOrderRefund;
use Biz\model\trade\ShopCourier as mShopCourier;
use Biz\model\trade\Order as mOrder;

class OrderPackage extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_trade';

    const _DATABASE_ = 'shop_trade';

    const _TABLE_NAME = 'order_package';

    public static function createPackage($uid, $orderNo, $skuIds = '', $expressCompany = '', $expressNo = '', $deliveryTime = "")
    {
        $lastOwnId = self::getLastOwnId($orderNo);

        $data = [
            'uid' => $uid,
            'own_id' => $lastOwnId,
            'order_no' => $orderNo,
            'sku_id_list' => $skuIds,
            'express_company' => $expressCompany,
            'express_no' => $expressNo,
        ];

        if (!empty($deliveryTime)) {
            $data['delivery_time'] = $deliveryTime;
        }else{
            $data['delivery_time'] = date("Y-m-d H:i:s");
        }

        self::insert($data);

        return self::id();

    }

    public static function getLastOwnId($orderNo)
    {
        $res = self::get(['own_id'], ['order_no' => $orderNo, 'ORDER' => ['own_id' => 'DESC']]);

        if (empty($res)) {
            return 1;
        }

        return $res['own_id'] + 1;


    }

    //结合此次发货的skuIds，判断是否全部发货完成
    public static function checkSendAll($orderNo, $nowSkuIds = [], $allSkuIds = [])
    {
        $skuIdList = $nowSkuIds;
        $allPackageSkuIds = self::getAllPackageSkuIds($orderNo);

        if (!empty($allPackageSkuIds)) {
            $skuIdList = array_merge($skuIdList, $allPackageSkuIds);
        }

        $skuIdList = array_unique($skuIdList);


        //获取退款成功的skuIDs
        $succRefundList = mOrderRefund::getRefundSuccessList($orderNo);
        if (!empty($succRefundList)) {
            $succRefundSkuIds = array_keys($succRefundList);

            $skuIdList = array_unique(array_merge($skuIdList, $succRefundSkuIds));
        }


        if (count($skuIdList) == count($allSkuIds)) {
            return true;
        }

        return false;

    }

    //修改包裹的快递信息

    public static function updatePackageExpressInfo($orderNo, $packageId, $expressCompany, $expressNo)
    {
        $result = self::update([
            'express_company' => $expressCompany,
            'express_no' => $expressNo
        ], ['order_no' => $orderNo, 'id' => $packageId]);

        if (is_object($result) && method_exists($result, 'rowCount')) {
            return $result->rowCount();
        }
        return 0;
    }

    //查询分单的物流单号信息
    public static function getPackageInfo($orderNo, $packageId)
    {
        return self::get('*', ['order_no' => $orderNo, 'id' => $packageId]);
    }


    public static function getFirstSkuInfo($orderNo, $packageId = 0)
    {
        if ($packageId > 0) {
            $info = self::getPackageInfo($orderNo, $packageId);

            if (empty($info)) {
                return [];
            }
            $skuIds = array_shift(array_filter(explode(',', $info['sku_id_list'])));

            $orderGoods = mOrderGoods::getSkuInfo($orderNo, $skuIds);

            return $orderGoods;

        } else {
            $orderGoods = mOrderGoods::getFirstSkuInfo($orderNo);

            return $orderGoods;
        }
    }


    public static function getPackageInfoList($orderNo)
    {
        return self::select('*', ['order_no' => $orderNo]);
    }


    public static function getAllPackageSkuIds($orderNo)
    {
        $packages = self::select('*', ['order_no' => $orderNo]);

        if (empty($packages)) {
            return [];
        }

        $skuIdList = [];

        array_map(function ($v) use (&$skuIdList) {
            $list = explode(',', $v);

            $skuIdList = array_merge($skuIdList, $list);

        }, array_filter(array_column($packages, 'sku_id_list')));

        $skuIdList = array_unique($skuIdList);

        return $skuIdList;
    }

    public static function checkSkuIdsDelivery($orderNo, $skuIds = [])
    {
        $packageSkuIds = self::getAllPackageSkuIds($orderNo);


        if (empty($packageSkuIds)) {
            return false;
        }

        $intersect = array_intersect($packageSkuIds, $skuIds);

        if (!empty($intersect)) {
            return true;
        }
        return false;
    }

    public static function getFirstPackageInfo($orderNo)
    {
        return self::get('*', ['order_no' => $orderNo, 'ORDER' => ['id' => 'ASC']]);
    }

    public static function getLastPackageInfo($orderNo)
    {
        return self::get('*', ['order_no' => $orderNo, 'ORDER' => ['id' => 'DESC']]);
    }

    public static function getExpressInfoList(array $orderNos): array
    {
        $expressList = [];
        $list = self::select(['express_company', 'express_no', 'order_no'], ['order_no' => $orderNos, 'ORDER' => ['id' => 'ASC']]);

        array_map(function ($v) use (&$expressList) {
            $expressList[$v['order_no']][] = $v;
        }, $list);

        return $expressList;
    }

    public static function getExpressCompanyList(array $orderNos): array
    {
        $expressList = self::getExpressInfoList($orderNos);

        $expressCompanyList = [];
        array_map(function ($v) use (&$expressCompanyList) {
            foreach ($v as $expressInfo) {
                $expressCompanyList[] = $expressInfo['express_company'];
            }
        }, $expressList);

        return [
            'expressList' => $expressList,
            'companyList' => $expressCompanyList,
        ];
    }
}